package com.rlz.framemm.util

import android.app.Activity
import android.app.Application
import android.app.Application.ActivityLifecycleCallbacks
import android.os.Bundle
import com.bumptech.glide.Glide
import java.util.*

/**
 * Created by RLZ
 * on 2021/10/21
 *
 */
class ActivityManager : ActivityLifecycleCallbacks {
    private var mResumed = 0
    private var mPaused = 0
    private var mStarted = 0
    private var mStopped = 0
    private var mActivityStack: Stack<Activity> = Stack()

    init {
        mResumed = 0
        mPaused = 0
        mStarted = 0
        mStopped = 0
    }

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        mActivityStack.add(activity)
    }


    override fun onActivityStarted(activity: Activity) {
        ++mStarted
    }


    override fun onActivityResumed(activity: Activity) {
        ++mResumed
    }

    override fun onActivityPaused(activity: Activity) {
        ++mPaused
    }

    override fun onActivityStopped(activity: Activity) {
        ++mStopped
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}

    override fun onActivityDestroyed(activity: Activity) {
        mActivityStack!!.remove(activity)
    }

    @Synchronized
    fun isApplicationVisible(): Boolean {
        return mStarted > mStopped
    }

    @Synchronized
    fun isApplicationInForeground(): Boolean {
        return mResumed > mPaused
    }

    @Synchronized
    fun isApplicationInBackground(): Boolean {
        return mStarted == mStopped
    }

    /**
     * 结束所有Activity
     */
    @Synchronized
    fun finishAllActivity() {
        var i = 0
        val size = mActivityStack!!.size
        while (i < size) {
            if (null != mActivityStack[i]) {
                mActivityStack[i]!!.finish()
            }
            i++
        }
        mActivityStack.clear()
    }

    /**
     * 退出应用程序
     */
    @Synchronized
    fun exitApp() {
        Glide.with(getCurrentActivity()!!.applicationContext)
            .setPauseAllRequestsOnTrimMemoryModerate(true)
        finishAllActivity()
    }

    /**
     * 结束当前的 Actoivity
     */
    @Synchronized
    fun finishTargetActivity(clazz: Class<out Activity?>) {
        val iterator = mActivityStack.iterator()
        while (iterator.hasNext()) {
            val activity = iterator.next()
            if (null != activity && activity.javaClass != clazz) {
                activity.finish()
                iterator.remove()
            }
        }
    }

    /**
     * 获取当前的Activity
     */
    @Synchronized
    fun getCurrentActivity(): Activity? {
        val index = mActivityStack.size - 1
        return if (index >= 0 && mActivityStack.size > index) {
            mActivityStack[index]
        } else null
    }

    /**
     * 获取Activity的 容器
     */
    @Synchronized
    fun getActivityStack(): Stack<Activity> {
        return mActivityStack
    }
}